package com.cyf.config;

import com.cyf.constant.DataSourceConstant;
import com.cyf.dao.AccountDao;
import com.cyf.dao.impl.AccountDaoImpl;
import com.cyf.service.AccountService;
import com.cyf.service.impl.AccountServiceImpl;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author cyf
 * @description
 * @create 2018-09-14 18:20
 **/
@Configuration
@EnableTransactionManagement
public class C3p0DataSourcePoolConfig {

    @Bean(name = DataSourceConstant.C3P0_DATASOUCE)
    @Qualifier
    public DataSource dataSource(){
        //c3p0 数据库连接池
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(DataSourceConstant.DRIVER_CLASS_NAME);
        dataSource.setUrl(DataSourceConstant.JDBC_URL);
        dataSource.setUsername(DataSourceConstant.USER_NAME);
        dataSource.setPassword(DataSourceConstant.PASS_WORD);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        return jdbcTemplate;
    }

    @Bean
    public AccountDao accountDao(){
        AccountDaoImpl accountDao = new AccountDaoImpl();
        accountDao.setJdbcTemplate(jdbcTemplate());
        return accountDao;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dataSource());
        return manager;
    }

    @Bean
    public AccountService accountService(){
        AccountServiceImpl accountService = new AccountServiceImpl();
        accountService.setDataSource(dataSource());
        accountService.setAccountDao(accountDao());
        return accountService;
    }


}
